package com.linsen.core.ohc.aspect;

import cn.hutool.core.util.ObjUtil;
import com.linsen.core.common.aspect.BaseAspect;
import com.linsen.core.common.constant.LinsenConstant;
import com.linsen.core.ohc.annotation.OHCachePut;
import com.linsen.core.ohc.util.OHCacheUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.time.Duration;

/**
 * @author zhaoyong
 * @date 2023/4/6
 */
@Slf4j
@Aspect
@Component
@RequiredArgsConstructor
public class OHCachePutAspect extends BaseAspect {
    private final OHCacheUtil<Object> ohCacheUtil;

    @Pointcut("@annotation(" + LinsenConstant.LINSEN_APP_PACKAGE + ".core.ohc.annotation.OHCachePut)")
    public void pointcut() {

    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        OHCachePut ohCachePut = super.getAnnotation(point, OHCachePut.class);
        String key = ohCachePut.key();

        Object result = point.proceed();
        if (ObjUtil.isNull(result)) {
            boolean isCacheNull = ohCachePut.isCacheNull();
            if (isCacheNull) {
                return null;
            }
        }

        if (ohCachePut.seconds() > 0L) {
            this.ohCacheUtil.set(key, result, Duration.ofSeconds(ohCachePut.seconds()));
        } else {
            this.ohCacheUtil.set(key, result);
        }

        return result;
    }
}
